/**
 * @file
 * SEARCH AUTOCOMPLETE javascript mechanism.
 *
 * Sponsored by:
 * www.axiomcafe.fr
 */

(function ($) {

  function strip(html)
  {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
  }
  $.ui.autocomplete.escapeRegex = function(value,inword){
    var reg = '';
    if(inword){
      reg =  value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }else{
      reg = '^' + value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }
    return reg;
  };
  $.ui.autocomplete.filter =  function(array, term,inword) {
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term,inword), "i" );
    return $.grep( array, function(value) {
      var kanzi = '';
      var pinyin = '';

      var compared = !!value.label ? value.label : (!!value.value ? value.value : value);
      var arr = compared.match(/(.+?)\((.+?)\)/i);
      if (!!arr && arr.length == 3) {
        kanzi = arr[1];
        pinyin = arr[2];
      }

      return matcher.test(kanzi) || matcher.test(pinyin);
    });
  };

  // Autocomplete
  $.ui.autocomplete.prototype._renderItem = function (ul, item) {
    var term = this.term;
    var first = ("group" in item)  ? 'first' : '';
    var innerHTML = '<div class="ui-autocomplete-fields ' + first + '">';
    item.value = strip(item.value);
    item.label = Drupal.checkPlain(item.label);
    if (item.fields) {
      $.each(item.fields, function(key, value) {
        var regex = new RegExp('(' + $.trim(term) + ')', 'gi');
        var output = Drupal.checkPlain(value);
        if (value.indexOf('src=') == -1 && value.indexOf('href=') == -1) {
          output = output.replace(regex, "<span class='ui-autocomplete-field-term'>$1</span>");
          innerHTML += ('<div class="ui-autocomplete-field-' + key + '">' + output + '</div>');
        } else {
          innerHTML += ('<div class="ui-autocomplete-field-' + key + '">' + value + '</div>');
        }
      });
    } else {
      innerHTML += ('<div class="ui-autocomplete-field">' + item.label + '</div>');
    }
    innerHTML += '</div>';

    var group = '';
    if ("group" in item) {
      groupId = typeof(item.group.group_id) !== 'undefined' ? item.group.group_id : '';
      groupName = typeof(item.group.group_name) !== 'undefined' ? item.group.group_name : '';
      group += ('<div class="ui-autocomplete-field-group ' + groupId + '">' + groupName + '</div>');
      $(group).appendTo(ul);
    }
    var elem =  $("<li class=ui-menu-item-" + first + "></li>" )
        .append("<a>" + innerHTML + "</a>");
    if (item.value == '') {
      elem = $("<li class='ui-state-disabled ui-menu-item-" + first + " ui-menu-item'>" + item.label + "</li>" );
    }
    elem.data("item.autocomplete", item).appendTo(ul);

    Drupal.attachBehaviors(elem);
    return elem;
  };

  $.ui.autocomplete.prototype._resizeMenu = function() {
    var ul = this.menu.element;
    ul.outerWidth(Math.max(ul.width("").outerWidth() + 5, this.options.position.of == null ? this.element.outerWidth() : this.options.position.of.outerWidth()));
  };

  Drupal.behaviors.search_autocomplete = {
    attach: function(context) {
      if (Drupal.settings.search_autocomplete) {
        $.each(Drupal.settings.search_autocomplete, function(key, value) {
          $(Drupal.settings.search_autocomplete[key].selector).bind("mouseover", function() {
            $(Drupal.settings.search_autocomplete[key].selector).addClass('form-autocomplete ui-autocomplete-processed').attr('data-sa-theme', Drupal.settings.search_autocomplete[key].theme).autocomplete({
              minLength: Drupal.settings.search_autocomplete[key].minChars,
              source: function(request, response) {
                $(Drupal.settings.search_autocomplete[key].selector).addClass('throbbing');
                // External URL:
                if (Drupal.settings.search_autocomplete[key].type == 'external') {
                  $.getJSON(Drupal.settings.search_autocomplete[key].datas, { q: encodeURIComponent(request.term) }, function (results) {
                    // Only return the number of values set in the settings.
                    if (results.length) {
                      results.slice(0, Drupal.settings.search_autocomplete[key].max_sug);
                    }
                    response(results);
                  });
                }
                // Internal URL:
                else if (Drupal.settings.search_autocomplete[key].type == 'internal' || Drupal.settings.search_autocomplete[key].type == 'view') {
                  var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
                  var validate = false;
                  if(reg.test(request.term)){
                    validate = true//含有中文
                  }else{
                    //不含中文
                    if(request.term.length >= 4){
                      validate = true;
                    }
                  }

                  if(validate){
                    if($("input[name='autocomplete_param_hidden']").length > 0 ){
                      request.param = $("input[name='autocomplete_param_hidden']").val();//获取额外参数
                    }
                    $.getJSON(Drupal.settings.search_autocomplete[key].datas, request, function (results) {
                      // Only return the number of values set in the settings.
                      if (results.length) {
                        results.slice(0, Drupal.settings.search_autocomplete[key].max_sug);
                      }
                      response(results);
                    });
                  }

                }
                // Static resources:
                else if (Drupal.settings.search_autocomplete[key].type == 'static') {
                  var results = $.ui.autocomplete.filter(Drupal.settings.search_autocomplete[key].datas, request.term,Drupal.settings.search_autocomplete[key].inword);
                  if (results.length) {
                    results.slice(0, Drupal.settings.search_autocomplete[key].max_sug);
                  }
                  response(results);
                }
              },
              open: function(event, ui) {
                $(".ui-autocomplete li.ui-menu-item:odd").addClass("ui-menu-item-odd");
                $(".ui-autocomplete li.ui-menu-item:even").addClass("ui-menu-item-even");
                $(Drupal.settings.search_autocomplete[key].selector).removeClass('throbbing');
              },
              select: function(event, ui) {

                if (Drupal.settings.search_autocomplete[key].auto_redirect == 1 && ui.item.link) {
                  document.location.href = ui.item.link;
                } else if (Drupal.settings.search_autocomplete[key].auto_submit == 1 && ui.item.value) {

                  if (typeof(ui.item.addr_id) != "undefined") {
                    if(ui.item.addr_id != -1){
                      $(this).val(ui.item.value);
                    }else{
                      return false;
                    }
                    if($("select[name='address_fuzzy_hidden']").length > 0 ){
                      $("select[name='address_fuzzy_hidden']").trigger("change");
                    }

                  }else{
                    $(this).val(ui.item.value);
                    if (new RegExp('(.*plant_measure/add)', 'i').test(window.location.pathname)) {
                      $(this).blur();
                    }
                  }

                  //$(this).closest("form").submit();
                }
              },
              focus: function (event, ui) {
                if (typeof ui.item.group != 'undefined') {
                  if (ui.item.group.group_id == 'no_results' || ui.item.group.group_id == 'all_results') {
                    event.preventDefault();
                  }
                }
              },
              appendTo: $(Drupal.settings.search_autocomplete[key].selector).parent()
            }).autocomplete("widget").attr("data-sa-theme", Drupal.settings.search_autocomplete[key].theme);
          });
          $(Drupal.settings.search_autocomplete[key].selector).trigger('mouseover');
        });
      }
    }
  };
})(jQuery);
